using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;


namespace TowerDefence
{
    public class AudioManager
    {
        private const string BgPath = "audio/bg/";
        
        private const string SoundPath = "audio/sound/";
        
        public static AudioSource BgAS;
        
        public static List<AudioSource> SoundASList=new List<AudioSource>();

        public static bool IsBgOn;
        
        public static bool IsSoundOn;

        public static void InitData()
        {
            IsBgOn = PlayerPrefs.GetInt("IsBgOn", 1) == 1;
            IsSoundOn = PlayerPrefs.GetInt("IsSoundOn", 1) == 1;
        }

        public static void SetBgOn(bool isOn)
        {
            IsBgOn = isOn;
            var value=IsBgOn?1:0;
            PlayerPrefs.SetFloat("IsBgOn", value);
            if (BgAS != null)
            {

                if (isOn)
                {
                    BgAS.Play();
                }
                else
                {
                    BgAS.Stop();
                }
            }
        }

        public static void SetSoundOn(bool isOn)
        {
            IsSoundOn = isOn;
            var value=IsSoundOn?1:0;
            PlayerPrefs.SetInt("IsSoundOn", value);
            for (int i = 0; i < SoundASList.Count; i++)
            {
                if (SoundASList[i].isPlaying)
                {
                    if (!IsSoundOn)
                    {
                        SoundASList[i].Stop();
                    }
                }
            }
        }

        public static void PlayBg(string name)
        {
            if (BgAS == null)
            {
                BgAS = Camera.main.AddComponent<AudioSource>();
            }
            BgAS.clip=Resources.Load<AudioClip>(BgPath+name);
            BgAS.loop = true;
            if(IsBgOn)
                BgAS.Play();
        }

        public static void PlaySound(string name)
        {
            AudioSource soundAs = null;
           
            for (int i = 0; i < SoundASList.Count; i++)
            {
                if (SoundASList[i].isPlaying == false)
                {
                    soundAs = SoundASList[i];
                  
                    break;
                }
            }
            if (soundAs == null)
            {
                soundAs = Camera.main.AddComponent<AudioSource>();
              
                SoundASList.Add(soundAs);
            }
            soundAs.clip=Resources.Load<AudioClip>(SoundPath+name);
            soundAs.loop = false;
            if(IsSoundOn)
                soundAs.Play();
        }
       
    }
}

